package sword.chapter11BinarySearch;

/**
 * 二分查找
 *
 * @author K
 * @date 2021-12-21 20:11
 */
public class BinarySearch {

    public static int search(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        while (left <= right) {
            int mid = (left + right) / 2;
            if (nums[mid] == target) {
                return mid;
            } else if (nums[mid] < target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        int[] nums = {2, 4, 6, 8, 10};
        int target = 4;
        int result = search(nums, target);
        System.out.println();
    }
}
